﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using OfficeOpenXml;
using System.Linq;
using static OfficeOpenXml.ExcelErrorValue;
using System.Windows.Media.Imaging;
namespace WindowsFormsApplication1

{
    public partial class Form1 : Form
    {

        #region    //初始化数据
        public Form1()
        {
            InitializeComponent();
            //this.Icon = new BitmapImage(new Uri("pack://application:,,,/Image/ModeBus.ico"));
        }
        StringBuilder Log = new StringBuilder();


        Boolean KeyEnable = true;  //工程或客户使用，工程就是TRUE


        string FilePath = @"\\192.168.13.9\戴普森\便携式BMS部\公共资料\2.BMS协议\BMS(MODBUS)协议规范.xlsx";
        public static Byte COM_HEAD1 = 0X55;
        public static Byte COM_HEAD2 = 0XAA;
        public static Byte Uart1_Salve_Local_Address = 0X00;

        private SerialPort ComDevice = new SerialPort();

        static public string ComName;  //端口号
        static public int ComBaudRate; //波特率可选（2400 4800 9600 14400 19200）
        static public int ComParity = 0;//奇偶校验可选（奇校验 偶检验 无校验）
        static public int ComDataBits;  //数据位
        static public StopBits ComStopBits;//停止位
        Parity[] parities = new Parity[] { Parity.None, Parity.Odd, Parity.Even,Parity.Mark,Parity.Space};
        int ConstComOverTime = 50;
        Boolean UpgradeDataState = false;
        int UpgradeDataOverTime;
        Byte[] UpgradeData;
        UInt32 UpgradeDataLength;
        Int32 UpgradePoint;
        UInt32 UpgradeOverTime;
        UInt32 UpgradeNumber;
        Boolean UpgradeState;
        Boolean UpgradeSuccess;
        Boolean UpgradeAck;
        Boolean ConnectionState;
        int ConnectionTime;
        Byte UpgradeType;
        Modebus.Crc16DataType UpgradeFileCrc;
        Boolean UartRecvStae = false;
        Byte[] PanlWriteData = new byte[32];
        Boolean PanlWriteState;
        Byte ComAddress = 0X00;
        List<string> Resume = new List<string>();
        Action<int, int,int,int> SetBaudType;
        private string _inputValue;
        public string InputValue { get => _inputValue; set { _inputValue = value; TextValue.Text = value; ComDevice.ReadTimeout = 3000; } }


        private void FormMain_Load(object sender, EventArgs e)
        {
            string path = FileType.GetAppPoint() + @"\Resume";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            if (File.Exists(path + "\\Resume.data"))
            {
                File.Delete(path + "\\Resume.data");
            }
            SetBaudType = ActionSetBaud;
            //Byte[] bytes = new Byte[] { 0X00, 0X02, 0X03, 0X04, 0X05, };
            string s = "123456789";
            button1.BackColor = Color.Red;
            button1.ForeColor = Color.White;
            PortNum.Items.Add(s);
            PortNum.Items.Clear();
            string[] str1 = StringOrder(SerialPort.GetPortNames());
            ComDevice.Close();
            string ComNum = (string)PortNum.SelectedItem;
            if (str1.Length != 0)
            {
                foreach (string s1 in str1)
                {
                    PortNum.Items.Add(s1);//获取有多少个COM口
                }
                PortNum.SelectedIndex = 0;
            }
            if (str1.Length != 0)
                ComDevice = new SerialPort(str1[0], 115200, parities[ComParity], 8, StopBits.One);
            ComDevice.DataReceived += new SerialDataReceivedEventHandler(ReceivedData);     //绑定事件
            ComDevice.ReadBufferSize = 1000000;

            Address.Items.Add("----");
            for (int i = 1; i <= 32; i++)
            {
                Address.Items.Add(" "+(i).ToString().PadLeft(2, '0')+" ");
            }
            Address.SelectedIndex = 0;
           
        }

        public string[] StringOrder(string[] str)  //字符串排序
        {
            for (int i = 0; i < str.Length - 1; i++)
            {
                for (int j = 0; j < str.Length - 1 - i; j++)
                {
                    //if (str[j].CompareTo(str[j + 1]) > 0) //字符串大小排序
                    if (Convert.ToInt32(System.Text.RegularExpressions.Regex.Replace(str[j], @"[^0-9]+", "")) > Convert.ToInt32(System.Text.RegularExpressions.Regex.Replace(str[j + 1], @"[^0-9]+", "")))
                    {
                        string s = str[j];
                        str[j] = str[j + 1];
                        str[j + 1] = s;
                    }
                }
            }
            return str;
        }
        public System.Windows.Forms.TextBox GetTextBoxes(int dex)
        {
            System.Windows.Forms.TextBox[] text = new System.Windows.Forms.TextBox[] 
            {
                ReGValue0, ReGValue1, ReGValue2,ReGValue3,ReGValue4,ReGValue5,ReGValue6,ReGValue7,ReGValue8,ReGValue9,
                ReGValue10, ReGValue11, ReGValue12,ReGValue13,ReGValue14,ReGValue15,ReGValue16,ReGValue17,ReGValue18,ReGValue19,
                ReGValue20, ReGValue21, ReGValue22,ReGValue23,ReGValue24,ReGValue25,ReGValue26,ReGValue27,ReGValue28,ReGValue29,
                ReGValue30, ReGValue31, ReGValue32,ReGValue33,ReGValue34,ReGValue35,
            };
            return text[dex];
        }
        public System.Windows.Forms.Label GetLable(int dex)
        {
            System.Windows.Forms.Label[] l = new System.Windows.Forms.Label[]
            {
                RegTitil0,  RegTitil1,  RegTitil2, RegTitil3, RegTitil4, RegTitil5, RegTitil6, RegTitil7, RegTitil8, RegTitil9,
                RegTitil10, RegTitil11, RegTitil12,RegTitil13,RegTitil14,RegTitil15,RegTitil16,RegTitil17,RegTitil18,RegTitil19,
                RegTitil20, RegTitil21, RegTitil22,RegTitil23,RegTitil24,RegTitil25,RegTitil26,RegTitil27,RegTitil28,RegTitil29,
                RegTitil30, RegTitil31, RegTitil32,RegTitil33,RegTitil34,RegTitil35,
            };
            return l[dex];
        }
        public System.Windows.Forms.Button GetButton(int dex)
        {
            System.Windows.Forms.Button[] button = new System.Windows.Forms.Button[]
            {
                ButSet0,  ButSet1,  ButSet2, ButSet3, ButSet4, ButSet5, ButSet6, ButSet7, ButSet8, ButSet9,
                ButSet10, ButSet11, ButSet12,ButSet13,ButSet14,ButSet15,ButSet16,ButSet17,ButSet18,ButSet19,
                ButSet20, ButSet21, ButSet22,ButSet23,ButSet24,ButSet25,ButSet26,ButSet27,ButSet28,ButSet29,
                ButSet30, ButSet31, ButSet32,ButSet33,ButSet34,ButSet35,
            };
            return button[dex];
        }
        

        public void SendDataFast(byte[] data)  //快速发送
        {
            if (ComDevice.IsOpen == true)
            {
                ComDevice.Write(data, 0, data.Length);
            }
            else
            {
                //MessageBox.Show("请先打开串口");
            }
        }
        List<byte[]> SerialPortData = new List<byte[]>();
        public Boolean SendData(Byte[] bytes)  //发送
        {
            SerialPortData.Add(bytes);
            return true;
        }

        private void comb_ComNum_Click(object sender, EventArgs e)  //单击时重新搜索新的串口
        {
            string[] str1 = StringOrder(SerialPort.GetPortNames());
            PortNum.Items.Clear();
            foreach (string s in str1)
            {
                PortNum.Items.Add(s);//获取有多少个COM口
            }
        }
        private void button1_Click(object sender, EventArgs e)//打开串口
        {
            if (button1.Text == "打开串口")  //这里是打开串口
            {
                try
                {
                    ComDevice.Close();
                    ComDevice = new SerialPort(SearcList[SearchPoint].Name, SearcList[SearchPoint].Baud, parities[ComParity], 8, StopBits.One);
                    ComDevice.DataReceived += new SerialDataReceivedEventHandler(ReceivedData);     //绑定事件
                    ComDevice.Open();
                    if (ComDevice.IsOpen)
                    {
                        button1.Text = "关闭串口";
                        button1.BackColor = Color.Green;
                    }
                    else
                    {
                        button1.Text = "打开串口";
                        button1.BackColor = Color.Red;
                    }
                }
                catch
                {
                    MessageBox.Show("串口打开失败！");
                }
            }
            else  //这里是关闭串口
            {
                ConnectionState = false;
                ComDevice.Close();
                button1.Text = "打开串口";
                button1.BackColor = Color.Red;
            }
        }
        #endregion

        #region  //基本数据

        public string UInt32ToFloat(UInt32 num)
        {
            string s1 = (num / 1000).ToString() + "." + (num % 1000).ToString();
            if (s1.Length < 7)
            {
                return s1.PadRight(7, '0');
            }
            else
            {
                return s1.Substring(0, 7);
            }
        }
        #endregion
        private void DecodingData(Byte[] ReData)  //串口接收
        {
            Byte[] Data = Modebus.DataIntercept(ReData, 4, ReData.Length - 6);
            if (BitConverter.ToUInt16(ReData, 0) == 0XAA55)
            {
                switch (ReData[3])
                {
                    case 0X0D:
                        MessageBox.Show(System.Text.Encoding.Default.GetString(Modebus.DataIntercept(Data, 0, ReData.Length - 2)), "软件版本");
                        break;

                    case 0X10:
                        MessageBox.Show("恢复初厂成功");
                        break;


                    case 0X11:
                        Uart1_Salve_Local_Address = Data[0];
                        switch(Data[1])
                        {
                            case 0: label3.ForeColor = System.Drawing.Color.Black; label3.Text = "状态:" + "N76和M031都已授权"; break;
                            case 1: label3.ForeColor = System.Drawing.Color.Red; label3.Text = "状态:" + "N76没有授权M031已授权"; break;
                            case 2: label3.ForeColor = System.Drawing.Color.Red; label3.Text = "状态:" + "N76已授权M031没有授权"; break;
                            case 3: label3.ForeColor = System.Drawing.Color.Red; label3.Text = "状态:" + "N76和M031都没有授权"; break;
                        }
                        if (Uart1_Salve_Local_Address != 0 && Uart1_Salve_Local_Address <= 32)
                        {
                            Address.SelectedIndex = Uart1_Salve_Local_Address;
                        }
                        break;
                    case 0X15:
                        
                        break; 

                    case 0X80:
                        MessageBox.Show(Data[0] == 0 ? "失败" : "成功"); break;
                    default: break;
                }
            }
            else
            {
                if (ReData[0] == 0X10)
                {
                    switch (ReData[1])
                    {
                        case 03:
                            Byte[] fcvByteData = new Byte[ReData.Length - 5];
                            
                            for (int i = 0; i < fcvByteData.Length; i++)
                            {
                                fcvByteData[i] = ReData[3 + i];
                            }
                            if (checkBox3.Checked == true && checkBox4.Checked == false)
                            {
                                for (int i = 0; i < fcvByteData.Length / 2; i++)
                                {
                                    GetTextBoxes(i).Text = ((Int16)((fcvByteData[2 * i] << 8) | (fcvByteData[2 * i + 1] << 0))).ToString();

                                }
                            }
                            else if (checkBox4.Checked == true && checkBox3.Checked == false)
                            {
                                for (int i = 0; i < fcvByteData.Length / 2; i++)
                                {
                                    GetTextBoxes(i).Text = $"0X{fcvByteData[2 * i]:X2} 0X{fcvByteData[2 * i + 1]:X2}";
                                }
                            }
                            break;

                        case 06:
                            checkBox2.Checked = true;
                            //MessageBox.Show("写入地址:" + ((Convert.ToUInt16(InputValue)+(ReData[2] << 8) + ReData[3]+1) - 1).ToString().PadLeft(2, '0') + "\r\n" + "写入值:" + ((ReData[4] << 8) + ReData[5]).ToString(),"操作结果");
                            break;
                    }
                }
                else
                {
                    //label2.Text = "收到错误地址";
                }
            }
        }

        
        int CountPortNum,CountPortBaud;



        struct PortType
        {
            public string Name;
            public Int32 Baud;
            public Parity Chek;

        }

        List<PortType> SearcList = new List<PortType>();
        Boolean SearchState = false;
        int SearchPoint = 0;

        int UartRecvLength;

        int TimeCount;

        private void ReceivedData(object sender, SerialDataReceivedEventArgs e)
        {
            UartRecvStae = true;
            TimeCount = 2;
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            if (UartRecvStae == true)
            {
                if (TimeCount != 0)
                {
                    TimeCount--;
                }
                else
                {
                    if (TimeCount == 0)
                    {
                        UartRecvStae = false;
                        if (ComDevice.IsOpen == true)
                        {
                            byte[] ReDatas = new byte[ComDevice.BytesToRead];
                            ComDevice.Read(ReDatas, 0, ReDatas.Length);     //读取数据 
                            if (Modebus.CheckCRC16(ReDatas) == true)
                            {
                                ConnectionTime = ConstComOverTime;
                                if (ConnectionState == false && checkBox1.Checked == true)
                                {
                                    ConnectionState = true;
                                    label4.Text = "串口连接成功";
                                    button1.Text = "关闭串口";
                                    button1.BackColor = Color.Green;
                                    string[] str1 = StringOrder(SerialPort.GetPortNames());
                                    if (str1.Length != 0)
                                    {
                                        foreach (string s1 in str1)
                                        {
                                            PortNum.Items.Add(s1);//获取有多少个COM口
                                        }
                                        PortNum.SelectedIndex = 0;
                                    }
                                    for (int i = 0; i < PortNum.Items.Count; i++)
                                    {
                                        if (ComDevice.PortName == (string)PortNum.Items[i])
                                        {
                                            PortNum.SelectedIndex = i;
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    DecodingData(ReDatas);
                                }
                            }
                            UartRecvStae = false;
                            UartRecvLength = 0;
                        }
                    }
                }
  
            }

        }

        private void checkBox4_CheckedChanged(object sender, EventArgs e)
        {
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            SystemTime++;
            if (ConnectionState == true)
            {
                TaskTime++;
                if (UpgradeDataState == false && SerialPortData.Count != 0)
                {
                    try
                    {
                        SendDataFast(SerialPortData[0]);
                    }
                    catch { }
                    SerialPortData.Remove(SerialPortData[0]);
                }
                else if (TaskTime > 5)
                {
                    TaskTime -= 5;
                    ModesDataState = !ModesDataState;
                    if (PanlWriteState == true)
                    {
                        PanlWriteState = false;
                        SendData(PanlWriteData);
                    }
                    else
                    {
                        if (UpgradeDataState == false)
                        {
                            if (SerialPortData.Count == 0)  //没有数据要发送时
                            {
                                if (ModesDataState == true)
                                {
                                    Task.Run(new System.Action(() =>
                                    {
                                        while (true)
                                        {
                                            while (WriteState == true)
                                                ReadState = false;
                                            FcvReadDataAddress = Convert.ToUInt16(InputValue);
                                            SendData(Modebus.ContinuousReading(0X10, FcvReadDataAddress, 36));
                                            Thread.Sleep(100);
                                            ReadState = true;
                                            Thread.Sleep(900);
                                        }
                                    }
                                    ));
                                }
                                else
                                {
                                    SendData(Modebus.DataPack(new byte[] { COM_HEAD1, COM_HEAD2, 0X00, 0X11 }, new byte[] { 0X03, 0X00, 0X00, 0X00, }));
                                }
                            }
                        }
                    }
                }
            }
            if (++SystemTime >= 10)
            {
                SystemTime = 0;
                label1.Text = System.DateTime.Now.ToString();

                if (checkBox2.Checked == false)
                {
                    if (++AutoRashTime > 20)
                    {
                        AutoRashTime = 0;
                        checkBox2.Checked = true;
                    }
                }
                else
                {
                    AutoRashTime = 0;
                }

            }
        }

        int AutoRashTime;

        private void timer3_Tick(object sender, EventArgs e)
        {

            if (ConnectionState == true) //连接
            {
                if (checkBox1.Checked == true)
                {
                    if (ConnectionTime == 0)
                    {
                        ConnectionState = false;
                        ComDevice.Close();
                        button1.Text = "打开串口";
                        button1.BackColor = Color.Red;
                        label4.Text = "连接断开";
                    }
                    else
                    {
                        if (UpgradeDataState == false)
                        {
                            ConnectionTime--;
                        }
                        else
                        {
                            if (UpgradeDataOverTime != 0)
                            {
                                UpgradeDataOverTime--;
                            }
                            else
                            {
                                UpgradeDataState = false;
                            }
                        }
                    }
                }
            }
            else    //如果没有连接
            {
                Address.SelectedIndex = 0;
                label3.ForeColor = System.Drawing.Color.Red; label3.Text = "状态:未知";
                if (checkBox1.Checked == true)
                {
                    if (SearcList.Count == 0)
                    {
                        string[] str1 = StringOrder(SerialPort.GetPortNames());
                        List<PortType> s = new List<PortType>();
                        for (int i = 0; i < str1.Length; i++)
                        {
                            PortType p = new PortType();
                            p.Name = str1[i]; p.Baud = 9600; p.Chek = Parity.None; s.Add(p);
                            p.Name = str1[i]; p.Baud = 9600; p.Chek = Parity.Odd; s.Add(p);
                            p.Name = str1[i]; p.Baud = 9600; p.Chek = Parity.Even; s.Add(p);
                            p.Name = str1[i]; p.Baud = 115200; p.Chek = Parity.None; s.Add(p);
                        }
                        SearcList = s;
                    }
                    else
                    {
                        try
                        {
                            ComDevice.Close();
                            ComDevice = new SerialPort(SearcList[SearchPoint].Name, SearcList[SearchPoint].Baud, SearcList[SearchPoint].Chek, 8, StopBits.One);
                            ComDevice.DataReceived += new SerialDataReceivedEventHandler(ReceivedData);     //绑定事件
                            ComDevice.Open();
                            if (ComDevice.IsOpen == true)
                            {
                                SendDataFast(Modebus.DataPack(new byte[] { 0X55, 0XAA, 0X00, 0X0F, 0X00, 0X00 }));
                            }
                        }
                        catch
                        {

                        }
                        finally
                        {
                            SearchPoint++;
                            if (SearchPoint == SearcList.Count)
                            {
                                SearchPoint = 0;
                                SearcList.Clear();
                            }
                        }
                    }
                }
            }
        }

        public UInt16 FcvReadDataAddress = 0;
        int TaskTime;
        int SystemTime;
        Boolean ModesDataState = false;



        private void ButSet_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Button btn = (System.Windows.Forms.Button)sender;
            if (!int.TryParse(InputValue, out _))
            {
                MessageBox.Show("输入起始位置为纯数字");
            }

            if (btn.Text == "读")
            {
                MessageBox.Show("此寄存器为只读", "警告！");
            }
            else 
            {
                UInt16 btnValue1 = Convert.ToUInt16(System.Text.RegularExpressions.Regex.Replace(btn.Name, @"[^0-9]+", ""));
                UInt16 Wrval = (ushort)Convert.ToSingle(DataOperation.StringReplaceNumber(GetTextBoxes((int)btnValue1).Text));
                UInt16 WrAdd = (ushort)(FcvReadDataAddress + btnValue1);
                if (label4.Text != "串口连接成功")
                {
                    MessageBox.Show("没有发现设备", "警告！");
                    return;
                }
                if (ConnectionState == true)
                {
               
                    if (checkBox4.Checked == false && checkBox3.Checked == false)
                    {
                        MessageBox.Show("请点击16进制显示或HEX显示！", "警告！");
                    }
                    else
                    {
                        PanlWriteState = true;
                        WriteState = true; ReadState = false;
                        Task.Run(new System.Action(() =>
                        {
                            int count = 0;
                            while (true)
                            {
                                while (ReadState == true)
                                WriteState = false;
                                SendData(Modebus.WriteSingle(0X10, WrAdd, Wrval));
                                Thread.Sleep(100);
                                WriteState = false;
                                Thread.Sleep(900);
                                ReadState = true;
                                ConnectionState = true;
                                timer2.Enabled = true;
                                count++;
                                if (count > 0) break;
                            }
                        }
                        ));
                        ConnectionState = true;
                        MessageBox.Show("写入成功！");
                        Thread.Sleep(500);
                        isInputting = false;
                    }
                }
                else
                {
                MessageBox.Show("请先连接设备！", "警告！");
                }
            }
        }


        Boolean WriteState = false,ReadState = true;
        public bool isInputting = false;
        private void ReGValue_MouseClick(object sender, MouseEventArgs e)
        {
            isInputting = true;
            ReadState = false;
            Task.Run(() =>
            {
                while (true)
                {
                    while (isInputting)
                    {
                        ConnectionState = false;
                        Thread.Sleep(900);
                        ConnectionState = true;
                        Thread.Sleep(500);
                        break;
                    }
                    isInputting = false;
                    ConnectionState = true;
                    break;
                }
            });
        }


        private void RegTitil34_Click(object sender, EventArgs e)
        {

        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }
        private void button5_Click(object sender, EventArgs e)
        {
            InputValue = TextValue.Text;
            FcvReadDataAddress = Convert.ToUInt16(InputValue);
            if (ConnectionState == false)
            {
                MessageBox.Show("没有发现设备", "警告！");
                return;
            }
            if (!int.TryParse(InputValue, out _))
            {
                MessageBox.Show("输入起始位置为纯数字");
            }
            else
            {
                ExcelPackage.License.SetNonCommercialPersonal("Your_Organization_Name");
                var excelFile = new FileInfo(FilePath);
                int tolil = FcvReadDataAddress + 35;

                if (tolil >= 10410)
                {
                    MessageBox.Show("超出字节范围", "警告！");
                    return;
                }
                using (var package = new ExcelPackage(excelFile))
                {
                    var ws = package.Workbook.Worksheets[0];
                    if (ws == null)
                    {
                        MessageBox.Show("未找到工作表", "警告！");
                        return;
                    }
                    for (int i = 0; i < 36; i++)
                    {
                        int currentAddress = FcvReadDataAddress + i;
                        if (currentAddress > tolil)
                        {
                            break;
                        }
                        int? rowNumber = FindRowNumber(FilePath, currentAddress);
                        if (rowNumber == null)
                        {
                            SetLabelText(i, "寄存器", currentAddress, "");
                            SetGetButton(i, "读", currentAddress);
                            continue;
                        }
                        int row = (int)rowNumber;
                        var cellCValue = ws.Cells[row, 3].Value?.ToString().Trim();
                        var cellDValue = ws.Cells[row, 4].Value?.ToString();
                        var cellstate = ws.Cells[row, 7].Value?.ToString();
                        var celluint = ws.Cells[row, 8].Value?.ToString();
                        if (cellCValue == null || cellDValue == null|| cellstate == null)
                        {
                            SetLabelText(i, "寄存器",currentAddress,"");
                            SetGetButton(i, "读", currentAddress);
                            continue;
                        }
                        if (Regex.IsMatch(cellCValue, @"^\d+\s*-\s*\d+$"))
                        {
                            var rangeParts = cellCValue.Split('-');
                            if (int.TryParse(rangeParts[0].Trim(), out int start) &&
                                int.TryParse(rangeParts[1].Trim(), out int end))
                                {
                                    for (int l = start; l <= end && i < 36; l++, i++)
                                    {
                                        int innerAddress = FcvReadDataAddress + i;
                                        if (innerAddress > tolil) break;
                                        if (FindRowNumber(FilePath, innerAddress) == null)
                                        {
                                            SetLabelText(i, "寄存器", innerAddress,"");
                                            SetGetButton(i, "读", innerAddress);
                                        }
                                        else
                                        {
                                            if (celluint == "/")
                                            {
                                                SetLabelText(i, cellDValue, innerAddress, "");
                                            }
                                            else
                                            {
                                                SetLabelText(i, cellDValue, innerAddress, celluint);
                                            }
                                            SetGetButton(i, cellstate, innerAddress);
                                        }
                                    }
                                    i--; 
                                }
                        }
                        else if (int.TryParse(cellCValue, out _))
                        {
                            if (celluint == "/")
                            {
                                SetLabelText(i, cellDValue, currentAddress, "");
                            }
                            else 
                            {
                                SetLabelText(i, cellDValue, currentAddress, celluint);
                            }
                            SetGetButton(i, cellstate, currentAddress);
                        }
                        else if (string.IsNullOrEmpty(cellCValue))
                        {
                            SetLabelText(i, "寄存器", currentAddress, "");
                            SetGetButton(i, "读", currentAddress);
                        }
                        else if (string.IsNullOrEmpty(cellDValue))
                        {
                            SetLabelText(i, "", currentAddress, "");
                            SetGetButton(i, "读", currentAddress);
                        }
                    }
                }

                void SetLabelText(int index, string prefix, int address,string suffix)
                {
                    string label = string.IsNullOrEmpty(prefix) ?
                        $"({address}):" :
                        $"{prefix} {suffix}({address})";
                    GetLable(index).Text = label;
                }
                void SetGetButton(int index, string prefix, int address)
                {
                    string label = string.IsNullOrEmpty(prefix) ?
                        $"({address}):" :
                        $"{prefix}";
                    GetButton(index).Text = label;
                }
            } 
        }

        private void RegTitil28_Click(object sender, EventArgs e)
        {

        }

        private void groupBox3_Enter(object sender, EventArgs e)
        {

        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void ReGValue24_TextChanged(object sender, EventArgs e)
        {

        }

        private void ActionSetBaud(int a, int b, int c, int d)
        {
            Byte[] bytes = new byte[16];
            bytes[0] = (Byte)(a >> 0); bytes[1] = (Byte)(a >> 8); bytes[2] = (Byte)(a >> 16); bytes[3] = (Byte)(a >> 24);
            bytes[4] = (Byte)(b >> 0); bytes[5] = (Byte)(b >> 8); bytes[6] = (Byte)(b >> 16); bytes[7] = (Byte)(b >> 24);
            bytes[8] = (Byte)(c >> 0); bytes[9] = (Byte)(c >> 8); bytes[10] = (Byte)(c >> 16); bytes[11] = (Byte)(c >> 24);
            bytes[12] = (Byte)(d >> 0); bytes[13] = (Byte)(d >> 8); bytes[14] = (Byte)(d >> 16); bytes[15] = (Byte)(d >> 24);
            SendData(Modebus.DataPack(new byte[] { COM_HEAD1, COM_HEAD2, 0X00, 0X12 }, bytes));
        }

        public int? FindRowNumber(string filePath, int targetNumber)
        {
            ExcelPackage.License.SetNonCommercialPersonal("Your_Organization_Name");
            using (var package = new ExcelPackage(new FileInfo(filePath)))
            {
                var ws = package.Workbook.Worksheets[0];
                for (int row = 3; row <= ws.Dimension.End.Row; row++)
                {
                    string cellValue = ws.Cells[row, 3].Text.Trim();
                    if (cellValue.Contains("-"))
                    {
                        var rangeParts = cellValue.Split('-');
                        if (rangeParts.Length == 2 &&
                            int.TryParse(rangeParts[0].Trim(), out int start) &&
                            int.TryParse(rangeParts[1].Trim(), out int end))
                        {
                            if (targetNumber >= start && targetNumber <= end)
                                return row;
                        }
                    }
                    else if (int.TryParse(cellValue, out int singleNumber))
                    {
                        if (targetNumber == singleNumber)
                            return row;
                    }
                    else if(string.IsNullOrEmpty(ws.Cells[row, row].Value?.ToString()))
                    {
                    }
                }
                return null; 
            }
        }
    }
}
